import { createMemoryHistory, createRouter, createWebHashHistory, Router } from 'vue-router';
import NProgress from 'nprogress';
import { storeToRefs } from 'pinia';
import { useRoutesList } from '@renderer/stores/routesList';
import { useKeepALiveNames } from '@renderer/stores/keepAliveNames';
import { staticRoutes, notFoundAndNoPower, dynamicRoutes } from '@renderer/router/route';
import { initFrontEndControlRoutes } from '@renderer/router/frontEnd';
import 'nprogress/nprogress.css';
import { Pinia } from 'pinia';

/**
 * 创建路由实例的工厂函数
 * @param pinia 当前应用的pinia实例
 * @returns 新的路由实例
 */
export function createRouterInstance(pinia: Pinia,nodeId=''): Router {
  console.log("router id")
  console.log("正在创建路由" + nodeId)
  const router = createRouter({
    history: createMemoryHistory(),
    routes: [
      ...notFoundAndNoPower,
      ...staticRoutes,
    ],
  });

  // 路由守卫
  router.beforeEach(async (to, from, next) => {
    NProgress.configure({ showSpinner: false });
    if (to.meta.title) NProgress.start();
    
    const storesRoutesList = useRoutesList(pinia);
    const { routesList } = storeToRefs(storesRoutesList);
    
    if (routesList.value.length === 0) {
      await initFrontEndControlRoutes(pinia, router);
      next({ path: to.path, query: to.query });
    } else {
      next();
    }
  });

  router.afterEach(() => {
    NProgress.done();
  });

  return router;
}

/**
 * 路由多级嵌套数组处理成一维数组
 * @param arr 传入路由菜单数据数组
 * @returns 返回处理后的一维路由菜单数组
 */
export function formatFlatteningRoutes(arr: any) {
  if (arr.length <= 0) return false;
  for (let i = 0; i < arr.length; i++) {
    if (arr[i].children) {
      arr = arr.slice(0, i + 1).concat(arr[i].children, arr.slice(i + 1));
    }
  }
  return arr;
}

/**
 * 格式化路由为两级结构
 * @param arr 路由数组
 * @param pinia 当前应用的pinia实例
 * @returns 格式化后的路由
 */
export function formatTwoStageRoutes(arr: any, pinia: Pinia) {
  if (arr.length <= 0) return false;
  const newArr: any = [];
  const cacheList: Array<string> = [];
  
  arr.forEach((v: any) => {
    if (v.path === '/') {
      newArr.push({ 
        component: v.component, 
        name: v.name, 
        path: v.path, 
        redirect: v.redirect, 
        meta: v.meta, 
        children: [] 
      });
    } else {
      if (v.path.indexOf('/:') > -1) {
        v.meta['isDynamic'] = true;
        v.meta['isDynamicPath'] = v.path;
      }
      newArr[0].children.push({ ...v });
      // 存 name 值，keep-alive 中 include 使用，实现路由的缓存
      if (newArr[0].meta.isKeepAlive && v.meta.isKeepAlive) {
        cacheList.push(v.name);
        const stores = useKeepALiveNames(pinia);
        stores.setCacheKeepAlive(cacheList);
      }
    }
  });
  
  return newArr;
}
    